<route lang="json5" type="page">
{
  needLogin: true,
  style: {
    navigationBarTitleText: '电费充值',
    enablePullDownRefresh: true
  },
}
</route>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

const keyword = ref('')
const waterMeters = ref<any[]>([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)

const allMeters = [
  { id: 1, remainingElectricity: '660.69', name: '501电表', meterId: '1000001', balance: '67.55' },
  { id: 2, remainingElectricity: '-60.69', name: '503电表', meterId: '1000022', balance: '-10.55' },
  { id: 3, remainingElectricity: '120.50', name: '504电表', meterId: '1000023', balance: '12.05' },
  { id: 4, remainingElectricity: '0.00', name: '505电表', meterId: '1000024', balance: '0.00' },
  { id: 5, remainingElectricity: '300.00', name: '506电表', meterId: '1000025', balance: '30.00' },
  { id: 6, remainingElectricity: '45.10', name: '507电表', meterId: '1000026', balance: '4.51' },
  { id: 7, remainingElectricity: '-20.00', name: '508电表', meterId: '1000027', balance: '-2.00' },
]

function fetchMeters(currentPage: number, searchKeyword: string) {
  return new Promise<any[]>((resolve) => {
    setTimeout(() => {
      let data = allMeters
      if (searchKeyword) {
        data = data.filter(
          m => m.name.includes(searchKeyword) || m.meterId.includes(searchKeyword),
        )
      }
      const pageSize = 5
      const start = (currentPage - 1) * pageSize
      const end = currentPage * pageSize
      resolve(data.slice(start, end))
    }, 800)
  })
}

async function loadData(isRefresh = false) {
  if (isRefresh) {
    page.value = 1
    finished.value = false
    waterMeters.value = []
  }

  if (loading.value || finished.value)
    return

  loading.value = true
  const newData = await fetchMeters(page.value, keyword.value)
  loading.value = false
  uni.stopPullDownRefresh()

  if (newData.length) {
    waterMeters.value.push(...newData)
    page.value++
  }
  else {
    finished.value = true
  }
}

function onSearch() {
  loadData(true)
}

function manageRecharge(meter: any) {
  //   uni.showToast({ title: `对 ${meter.name} 进行充值管理`, icon: 'none' })
  uni.navigateTo({
    url: `/pages-user/user/electricityRecharge/recharge?meterId=${meter.meterId}&name=${meter.name}&balance=${meter.balance}&remainingElectricity=${meter.remainingElectricity}`,
  })
}

function issueRefund(meter: any) {
  uni.showToast({ title: `对 ${meter.name} 进行退费`, icon: 'none' })
}

onLoad(() => {
  uni.showLoading({ title: '加载中...' })
  loadData().finally(() => {
    uni.hideLoading()
  })
})

onPullDownRefresh(() => {
  loadData(true)
})

onReachBottom(() => {
  loadData()
})
</script>

<template>
  <view class="min-h-screen">
    <!-- 搜索栏 -->
    <wd-search v-model="keyword" placeholder="请输入关键字!" light hide-cancel @search="onSearch" />

    <!-- 水表列表 -->
    <view class="p-3">
      <wd-card v-for="meter in waterMeters" :key="meter.id" custom-class="!p-0 mb-3">
        <view class="p-4">
          <view class="mb-3 flex items-center justify-between text-sm">
            <text class="text-gray-600">
              电表名称
            </text>
            <text class="text-gray-800">
              {{ meter.name }}
            </text>
          </view>
          <view class="mb-3 flex items-center justify-between text-sm">
            <text class="text-gray-600">
              表号
            </text>
            <text class="text-gray-800">
              {{ meter.meterId }}
            </text>
          </view>
          <view class="mb-3 flex items-center justify-between">
            <text class="text-gray-600">
              剩余电量
            </text>
            <view class="flex items-baseline">
              <text
                class="text-lg font-bold"
                :class="{
                  'text-red-500': parseFloat(meter.remainingElectricity) < 0,
                  'text-black': parseFloat(meter.remainingElectricity) >= 0,
                }"
              >
                {{ meter.remainingElectricity }}
              </text>
              <text class="ml-1 text-sm font-bold">
                度
              </text>
            </view>
          </view>
          <view class="flex items-center justify-between text-sm">
            <text class="text-gray-600">
              表余额
            </text>
            <text
              class="text-gray-800"
              :class="{
                'text-red-500': parseFloat(meter.balance) < 0,
              }"
            >
              {{ meter.balance }}
            </text>
          </view>
        </view>
        <view class="flex items-center justify-end border-t border-gray-100 p-3">
          <wd-button size="small" custom-class="!mr-2" @click="manageRecharge(meter)">
            充值管理
          </wd-button>
          <wd-button type="info" size="small" custom-class="!ml-2" @click="issueRefund(meter)">
            退费
          </wd-button>
        </view>
      </wd-card>

      <!-- 加载状态 -->
      <view class="py-4 text-center text-sm text-gray-500">
        <text v-if="loading">
          加载中...
        </text>
        <text v-else-if="finished">
          没有更多了
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
/* 可以在这里添加额外的样式 */
</style>
